package com.kehutong.charge.service.impl;

import com.kehutong.charge.entity.ChargeTypeConfig;
import com.kehutong.charge.entity.MeterClassify;
import com.kehutong.charge.entity.MeterManage;
import com.kehutong.charge.entity.MeterTypeConfig;
import com.kehutong.charge.service.ChargeTypeService;
import com.kehutong.charge.util.enums.MeterTypeEnum;
import com.kehutong.common.constant.CommonConstant;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.BigDecimalUtils;
import org.coraframework.boot.annotation.Initialize;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: kht
 * @description: ChargeTypeServiceImpl
 * @author: joneron
 * @create: 2021/6/23
 **/
public class ChargeTypeServiceImpl implements ChargeTypeService {

    private static final Logger logger = LoggerFactory.getLogger(ChargeTypeServiceImpl.class);
    /**兼容老数据ID*/
    private static final Map<String,String> DEFAULT_FEE_TYPE = new HashMap<>();
    static {
        DEFAULT_FEE_TYPE.put("天然气","162683288095810006");
        DEFAULT_FEE_TYPE.put("水表",  "162677288357510000");
        DEFAULT_FEE_TYPE.put("电表",  "162683286736010005");
    }



    @Inject
    private JdbcSession jdbcSession;



    @Override
    public Page<ChargeTypeConfig> findPage(JSONObject jsonObject) {
        this.initDefaultType();

        FindPage<ChargeTypeConfig> find = jdbcSession.findPage(ChargeTypeConfig.class)
                .eq("deleted", false)
                .like(jsonObject,"feeTypeName")
                .eq(jsonObject,"status")
                .eq(jsonObject,"communityNo")
                .order("sort", "desc")
                .order("createTime", "desc");

        find.page(jsonObject);
        Page<ChargeTypeConfig> result = find.exe();
        if(Objects.isEmpty(result.getList())){
            return result;
        }
        //todo 临时性多余功能
        List<ChargeTypeConfig> list = result.getList();
        for (ChargeTypeConfig each : list) {
            if (each.isInitData()) {
                each.setCommunityName(CommonConstant.DEFAULT_COMMUNITY_NAME);
                each.setCreateName("系统");
            }
        }
        return result;
    }


    @Override
    public List<ChargeTypeConfig> findList(JSONObject jsonObject) {
        String communityNo = jsonObject.getString("communityNo");
        FindArray<ChargeTypeConfig> chargeTypeConfigFindArray = jdbcSession.findArray(ChargeTypeConfig.class)
                .eq("deleted", false);
        if (!Objects.isBlank(communityNo)) {
            chargeTypeConfigFindArray.eq("communityNo", communityNo);
            chargeTypeConfigFindArray.eq("status", true);
        }
        List<ChargeTypeConfig> chargeTypeConfigList = chargeTypeConfigFindArray.exe();
        if (Objects.isEmpty(chargeTypeConfigList)) {
            chargeTypeConfigList = jdbcSession.findArray(ChargeTypeConfig.class)
                    .eq("deleted", false).eq("communityNo", CommonConstant.DEFAULT_COMMUNITY_NO).eq("status", true).exe();
        }
        if (!Objects.isEmpty(chargeTypeConfigList)) {
            List<String> meterTypeConfigIdList = new ArrayList<>();
            for (ChargeTypeConfig each : chargeTypeConfigList) {
                meterTypeConfigIdList.add(each.getMeterTypeNo());
            }
            List<MeterTypeConfig> meterTypeConfigList = jdbcSession.findArray(MeterTypeConfig.class).in("id", meterTypeConfigIdList).exe(false);
            Map<String, MeterTypeConfig> meterTypeConfigMap = meterTypeConfigList.stream().collect(Collectors.toMap(MeterTypeConfig::getId, Function.identity()));
            for (ChargeTypeConfig each : chargeTypeConfigList) {
                each.setMeterTypeConfig(meterTypeConfigMap.get(each.getMeterTypeNo()));
            }
        }
        return chargeTypeConfigList;
    }


    /**
     * 初始化收费类型设置
     */
    private void initDefaultType(){
        List<MeterTypeConfig> dbMeterTypes = jdbcSession.findArray(MeterTypeConfig.class).eq("deleted", false).exe();
        if(Objects.isEmpty(dbMeterTypes)){
            throw new RuntimeException("需要先创建[仪表管理-仪表类型]才能进行初始化收费类型设置");
        }
        Set<String> dbMeterTypeIds = dbMeterTypes.stream().map(m -> m.getId()).collect(Collectors.toSet());
        List<ChargeTypeConfig> findFeeTypes = jdbcSession.findArray(ChargeTypeConfig.class)
                 //.eq("deleted", false) //需求变更，删除后的数据不可二次初始化
                .eq("communityNo", CommonConstant.DEFAULT_COMMUNITY_NO)
                .in("meterTypeNo", dbMeterTypeIds)
                .eq("initData", true)
                .exe();
        if(!Objects.isEmpty(findFeeTypes)){
            return;
        }
        //有多少个仪表类型就初始化多少个收费类型配置
        List<ChargeTypeConfig> insertList = new ArrayList<>();
        for (MeterTypeConfig meterType : dbMeterTypes) {
            ChargeTypeConfig typeConfig = Pool.newInstance(ChargeTypeConfig.class);
            //兼容老数据ID
            String typeName = meterType.getTypeName();
            String oldId = DEFAULT_FEE_TYPE.keySet().stream().filter(d -> d.equals(typeName))
                    .map(d -> DEFAULT_FEE_TYPE.get(typeName)).findFirst().orElse(null);
            if(!Objects.isEmpty(oldId)){
                typeConfig.setId(oldId);
            }

            typeConfig.setFeeTypeName(typeName+"(系统生成)");
            typeConfig.setMeterTypeNo(meterType.getId());
            typeConfig.setMeterTypeName(typeName);
            typeConfig.setScaleRatio(BigDecimalUtils.format("100"));
            typeConfig.setCommunityNo(CommonConstant.DEFAULT_COMMUNITY_NO);
            typeConfig.setCommunityName(CommonConstant.DEFAULT_COMMUNITY_NAME);
            typeConfig.setCreateName("System");
            typeConfig.setInitData(true);
            typeConfig.setStatus(true);
            typeConfig.setSort(999);
            insertList.add(typeConfig);
        }
        jdbcSession.insert(insertList);
    }


    @Override
    public Object save(ChargeTypeConfig config) {
        if(CommonConstant.DEFAULT_COMMUNITY_NAME.equals(config.getCommunityNo())){
            //如果是添加默认配置
            config.setCommunityNo(CommonConstant.DEFAULT_COMMUNITY_NO);
            config.setInitData(true);
            config.setSort(999);
        }
        config.setStatus(true);
        return jdbcSession.insert(config);
    }


    @Override
    public Object update(ChargeTypeConfig chargeTypeConfig) {
        if(chargeTypeConfig.isInitData() && !CommonConstant.DEFAULT_COMMUNITY_NO.equals(chargeTypeConfig.getCommunityNo())){
            throw new RuntimeException("系统初始化数据不能修改ID.");
        }
        return jdbcSession.updateById(chargeTypeConfig);
    }


    @Override
    public Object deleteById(String id) {
        ChargeTypeConfig result = Pool.get(ChargeTypeConfig.class, id);
        if (result == null) {
            return 0;
        }
        result.setDeleted(true);
        return jdbcSession.updateById(result);
    }
}
